package com.wing.common.utils;
import com.wing.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import javax.imageio.ImageIO;
import javax.print.*;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.*;
import java.awt.image.BufferedImage;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PrintUtil {

    public static void main(String[] argv) throws Exception {
        String a = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAByUlEQVR42u3cW66CQBBFUeY/aR2Awch5VDe4+1NvuPQiFPUgHi/Wz+uAACywwALrb7AOb30e59InX85H+8rcBVhgrcW6dj+fQ2gnF78w2i7AAmsTLPN0ta/MuJbaBVhg3RqrF+m0rAIssMCSk4leDAULrBthpaJPPDDJufgNyh2wwFrXz4p/8uTmH1jPxYrNQtKP/FRg2nEUBhZYP297OGN2+MzONVhg7YY1GSy0vN9sNOsZPFhgdbBSd7tZSJstYzMEgwXWWqzGvykFnVTCUSl3wALLwDLv/yV5dnzaChZYm2DFa9qBYUzq4oEF1m5YqZq2F5hmGs1ggTWGpW3SjCNr334ItJXBAqvzNOwVruaRzUJiWbkDFlhlrNQmTZrqxQMLrHks7QHf6zqlrpCcgoAF1kKsgad4PCwui1lggVXG0urnVEWtpSDd9+DBAquDFWvChl4MioPKfwMWWGNY8bs9Hke0amHolSOwwOoMWWdmJwJxfP5aybPAAmuD388y+cyBjZlwgAXWM7BSlXBqzNNNHcACa2+sXs9La2pPD1nBAmun2tCsus0jgwXWjbB6/Swz0plt7koGDxZYUSwWWGCBBRZYYLHO1hv/nbo6Gxi6WgAAAABJRU5ErkJggg==";
        File file = new File( uploadPhoto("测试",a,".jpg"));
        String printerName = "HPRT N51";//打印机名包含字串
            JPGPrint(file,printerName);
        //file.delete();
    }
    /**
     9      * 将图片保存到项目路径下
     10      *
     11      * @param photoName 图片名称
     12      * @param photoData 图片资源
     13      * @param type 文件类型
     14      * @return 图片路径
     15      * @throws Exception
     16      */
     public static String uploadPhoto(String photoName, String photoData, String type)
             throws Exception {
                // 去掉base64前缀 data:image/jpeg;base64,
                photoData =  photoData.substring(photoData.indexOf(",", 1) + 1);
                // 对图片进行Base64解码
                 byte[] b = Base64.decodeBase64(photoData);
                 for (int i = 0; i < b.length; i++)
                     {
                         if(b[i] < 0)
                             {    //调整异常数据
                                 b[i] += 256;
                             }
                     }
                 // 生成图片
                 // 项目路径
         File directory = new File("core-center/common-core/src/main/resources");
         String reportPath = directory.getCanonicalPath();
         String resource =reportPath + "/static/codeImage/";
                 String filePath = resource + photoName + type;
                 File file = new File(filePath);
                 // 获取父文件
                File parent = file.getParentFile();
                // 若不存在创建父文件夹
                if (!parent.exists()) {
                         parent.mkdirs();
                     }

                 // 输出文件流
                 OutputStream out = new FileOutputStream(file);
                 out.write(b);
                 out.flush();
                 out.close();
                 return filePath;
             }

    public static void JPGPrint(File file,String printerName) throws PrintException {
        if (file == null) {
            throw new BusinessException("缺少打印文件");
        }
        InputStream fis = null;
        try {
            // 设置打印格式，如果未确定类型，可选择autosense
            DocFlavor flavor = DocFlavor.INPUT_STREAM.JPEG;
            // 设置打印参数
            PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
            DocAttributeSet das = new HashDocAttributeSet();
            aset.add(new Copies(1)); //份数
            aset.add(new MediaPrintableArea(28,3,40,25,MediaPrintableArea.MM)); //纸张
            // aset.add(Finishings.STAPLE);//装订
            //aset.add(Sides.DUPLEX);//单双面
            // 定位打印服务
            PrintService printService = null;
            if (printerName != null) {
                //获得本台电脑连接的所有打印机
                PrintService[] printServices = PrinterJob.lookupPrintServices();
                if(printServices == null || printServices.length == 0) {
                    throw new BusinessException("打印失败，未找到可用打印机，请检查!");
                }
                //匹配指定打印机
                for (int i = 0;i < printServices.length; i++) {
                    System.out.println(printServices[i].getName());
                    if (printServices[i].getName().contains(printerName)) {
                        printService = printServices[i];
                        break;
                    }
                }
                if(printService==null){
                    throw new BusinessException("打印失败，未找到名称为" + printerName + "的打印机，请检查!");
                }
            }
            fis = new FileInputStream(file); // 构造待打印的文件流
            Doc doc = new SimpleDoc(fis, flavor, das);
            DocPrintJob job = printService.createPrintJob(); // 创建打印作业
            job.print(doc, aset);
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } finally {
            // 关闭打印的文件流
            if (fis != null) {
                try {
                    file.delete();
                    fis.close();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
